﻿namespace OnlineVideos.RingToneEditor
{
    using System;
    using System.IO;
    using System.Runtime.InteropServices;

  
    public class AdpcmWaveFormat : WaveFormat
    {
        private short samplesPerBlock;
        private short numCoeff;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst=14)]
        private short[] coefficients;
        private AdpcmWaveFormat() : this(0x1f40, 1)
        {
        }

        public int SamplesPerBlock
        {
            get
            {
                return this.samplesPerBlock;
            }
        }
        public int NumCoefficients
        {
            get
            {
                return this.numCoeff;
            }
        }
        public short[] Coefficients
        {
            get
            {
                return this.coefficients;
            }
        }
        public AdpcmWaveFormat(int sampleRate, int channels) : base(sampleRate, 0, channels)
        {
            base.waveFormatTag = WaveFormatEncoding.Adpcm;
            base.extraSize = 0x20;
            switch (base.sampleRate)
            {
                case 0x5622:
                    base.blockAlign = 0x200;
                    break;

                case 0x1f40:
                case 0x2b11:
                    base.blockAlign = 0x100;
                    break;

                default:
                    base.blockAlign = 0x400;
                    break;
            }
            base.bitsPerSample = 4;
            this.samplesPerBlock = (short) ((((base.blockAlign - (7 * channels)) * 8) / (base.bitsPerSample * channels)) + 2);
            base.averageBytesPerSecond = (base.SampleRate * base.blockAlign) / this.samplesPerBlock;
            this.numCoeff = 7;
            this.coefficients = new short[] { 0x100, 0, 0x200, -256, 0, 0, 0xc0, 0x40, 240, 0, 460, -208, 0x188, -232 };
        }

        public override void Serialize(BinaryWriter writer)
        {
            base.Serialize(writer);
            writer.Write(this.samplesPerBlock);
            writer.Write(this.numCoeff);
            foreach (short num in this.coefficients)
            {
                writer.Write(num);
            }
        }

        public override string ToString()
        {
            return string.Format("Microsoft ADPCM {0} Hz {1} channels {2} bits per sample {3} samples per block", new object[] { base.SampleRate, base.channels, base.bitsPerSample, this.samplesPerBlock });
        }
    }
}

